package com.ruoyi.teaching.service.impl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.teaching.domain.YaClass;
import com.ruoyi.teaching.domain.YaCourseDesign;
import com.ruoyi.teaching.dto.YaTeachingPlanDTO;
import com.ruoyi.teaching.mapper.YaCourseDesignMapper;
import com.ruoyi.teaching.service.IYaClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.teaching.mapper.YaTeachingPlanMapper;
import com.ruoyi.teaching.domain.YaTeachingPlan;
import com.ruoyi.teaching.service.IYaTeachingPlanService;
import scala.util.Success;

/**
 * 教学计划Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-16
 */
@Service
public class YaTeachingPlanServiceImpl implements IYaTeachingPlanService {
  @Autowired
  private YaTeachingPlanMapper yaTeachingPlanMapper;

  /**
   * 查询教学计划
   *
   * @param id 教学计划主键
   * @return 教学计划
   */
  @Override
  public YaTeachingPlan selectYaTeachingPlanById(Long id) {
    return yaTeachingPlanMapper.selectYaTeachingPlanById(id);
  }

  /**
   * 查询教学计划列表
   *
   * @param yaTeachingPlan 教学计划
   * @return 教学计划
   */
  @Override
  public List<YaTeachingPlan> selectYaTeachingPlanList(YaTeachingPlan yaTeachingPlan) {
    return yaTeachingPlanMapper.selectYaTeachingPlanList(yaTeachingPlan);
  }

  /**
   * 新增教学计划
   *
   * @param yaTeachingPlan 教学计划
   * @return 结果
   */
  @Override
  public int insertYaTeachingPlan(YaTeachingPlan yaTeachingPlan) {
    YaTeachingPlan plan = new YaTeachingPlan();
    plan.setDate(yaTeachingPlan.getDate());
    plan.setDay(yaTeachingPlan.getDay());
    plan.setClassName(yaTeachingPlan.getClassName());
    List<YaTeachingPlan> list = yaTeachingPlanMapper.selectYaTeachingPlanList(plan);
    if (!list.isEmpty()) {
      throw new ServiceException("该日期已存在计划", 200);
    }
    return yaTeachingPlanMapper.insertYaTeachingPlan(yaTeachingPlan);
  }

  /**
   * 修改教学计划
   *
   * @param yaTeachingPlan 教学计划
   * @return 结果
   */
  @Override
  public int updateYaTeachingPlan(YaTeachingPlan yaTeachingPlan) {
    return yaTeachingPlanMapper.updateYaTeachingPlan(yaTeachingPlan);
  }

  /**
   * 批量删除教学计划
   *
   * @param ids 需要删除的教学计划主键
   * @return 结果
   */
  @Override
  public int deleteYaTeachingPlanByIds(Long[] ids) {
    return yaTeachingPlanMapper.deleteYaTeachingPlanByIds(ids);
  }

  /**
   * 删除教学计划信息
   *
   * @param id 教学计划主键
   * @return 结果
   */
  @Override
  public int deleteYaTeachingPlanById(Long id) {
    return yaTeachingPlanMapper.deleteYaTeachingPlanById(id);
  }

  /**
   * 查询已有计划
   *
   * @param yaTeachingPlan
   * @return
   */
  @Override
  public List<YaTeachingPlan> selectYaTeachingPlanListAll(YaTeachingPlanDTO yaTeachingPlan) {
    return yaTeachingPlanMapper.selectYaTeachingPlanListAll(yaTeachingPlan);
  }

  @Autowired
  private IYaClassService iYaClassService;
  @Autowired
  private YaCourseDesignMapper yaCourseDesignMapper;

  /**
   * 重新创建预览
   *
   * @param plan YaTeachingPlan实体
   * @return 返回结果
   */
  @Autowired
  private StringRedisTemplate redisTemplate;

  @Override
  public List<YaTeachingPlan> previewTeachingPlan(YaTeachingPlanDTO yaTeachingPlanDTO) {
    String className = yaTeachingPlanDTO.getClassName();
    String beginDate = yaTeachingPlanDTO.getBeginDate();
//    根据阶段、班级名称、开始时间查询已有计划
    List<YaTeachingPlan> list = yaTeachingPlanMapper.selectYaTeachingPlanListAll(yaTeachingPlanDTO);
//    获取到最后一个有课程的计划，而不是节假日，节假日是没有课程和day的
    YaTeachingPlan plan2 = new YaTeachingPlan();
    if (list.isEmpty()) {
      plan2 = null;
    } else {
      for (int i = list.size() - 1; i >= 0; i--) {
        plan2 = list.get(i);
        if (null != plan2.getDay()) {
          break;
        }
      }
    }
    YaTeachingPlan plan1 = list.isEmpty() ? null : list.get(list.size() - 1);
//    构建新计划
    YaTeachingPlan plan = new YaTeachingPlan();
//    如果最后一个计划为空，那就说明是第一次创建计划
    if (null == plan1) {
//      根据阶段查询出阶段的所有课程
      List<YaCourseDesign> courseDesigns = yaCourseDesignMapper.selectYaCourseDesignByStageId(yaTeachingPlanDTO.getStage().longValue());
      YaCourseDesign design = new YaCourseDesign();
      if (courseDesigns.isEmpty()) {
        throw new ServiceException("该阶段暂无课程", 200);
      } else {
        design = courseDesigns.get(0);
      }
      plan.setDate(beginDate);
      plan.setDay(design.getDay());
      LocalDate date = LocalDate.parse(beginDate);
      int weekday = date.getDayOfWeek().getValue();
      plan.setWeekday(weekday);
    } else {
      LocalDate date = LocalDate.parse(plan1.getDate());
      LocalDate date1 = date.plusDays(1);
      String format = date1.format(DateTimeFormatter.ISO_LOCAL_DATE);
      plan.setDate(format);
      plan.setDay(plan2.getDay() + 1);
      if (plan1.getWeekday() == 7) {
        plan.setWeekday(1);
      } else {
        plan.setWeekday(plan1.getWeekday() + 1);
      }
    }

    YaClass yaClass = iYaClassService.selectYaClassByClassName(className);
    if (null != yaClass) {
      plan.setClassesId(yaClass.getId());
      //    休息日
      Integer restDay = yaClass.getRestDay();
      //    自习日
      Integer selfStudyDay = yaClass.getSelfStudyDay();
      if (restDay.equals(plan.getWeekday())) {
        plan.setCourseContent("休息");
        plan.setDay(null);
      } else if (selfStudyDay.equals(plan.getWeekday())) {
        plan.setCourseContent("自习");
        plan.setDay(null);
      } else {
        YaCourseDesign yaCourseDesign = yaCourseDesignMapper.selectYaCourseDesignByDay(plan.getDay());
        if (null == yaCourseDesign) {
          throw new ServiceException("该天暂无课程", 200);
        }
        plan.setCourseContent(yaCourseDesign.getCourseContent());
        plan.setCourseDesignId(yaCourseDesign.getId());
      }
    }
    plan.setClassName(className);
    plan.setStage(yaTeachingPlanDTO.getStage());
    list.add(plan);
    return list;
  }


  /**
   * 添加工作日
   *
   * @param yaTeachingPlan
   * @return
   */
  @Override
  public List<YaTeachingPlan> addWorkday(YaTeachingPlan yaTeachingPlan) {
    // 创建查询条件
    YaTeachingPlanDTO queryDTO = new YaTeachingPlanDTO();
    queryDTO.setClassName(yaTeachingPlan.getClassName());
    queryDTO.setStage(yaTeachingPlan.getStage());

    // 查询当前班级和阶段的所有计划
    List<YaTeachingPlan> list = yaTeachingPlanMapper.selectYaTeachingPlanListAll(queryDTO);

    // 查找要修改的计划项
    YaTeachingPlan targetPlan = null;
    for (YaTeachingPlan plan : list) {
      if (plan.getDate().equals(yaTeachingPlan.getDate())) {
        targetPlan = plan;
        break;
      }
    }

    // 如果找到了目标计划，且是休息日或自习日，则改为工作日
    if (targetPlan != null &&
      ("休息".equals(targetPlan.getCourseContent()) || "自习".equals(targetPlan.getCourseContent()))) {

      // 获取班级信息
      YaClass yaClass = iYaClassService.selectYaClassByClassName(yaTeachingPlan.getClassName());
      if (yaClass != null) {
        targetPlan.setClassesId(yaClass.getId());

        // 查找前一个有效教学日来确定当前是第几天

        YaTeachingPlan previousPlan = findLastValidPlan(list, targetPlan.getDate());

        if (previousPlan != null && previousPlan.getDay() != null) {
          targetPlan.setDay(previousPlan.getDay() + 1);
        } else {
          // 如果找不到之前的教学日，从第一天开始
          targetPlan.setDay(1L);
        }

        // 根据天数获取课程内容
        YaCourseDesign courseDesign = yaCourseDesignMapper.selectYaCourseDesignByDay(targetPlan.getDay());
        if (courseDesign != null) {
          targetPlan.setCourseContent(courseDesign.getCourseContent());
          targetPlan.setCourseDesignId(courseDesign.getId());
        }

        // 更新后续所有计划的天数，确保连续性
        updateSubsequentPlans(list, targetPlan);

        // 更新数据库中的记录（如果已存在）
        if (targetPlan.getId() != null) {
          yaTeachingPlanMapper.updateYaTeachingPlan(targetPlan);
        }
      }
    }
    return list;
  }

  /**
   * 查找指定日期之前最后一个有效教学计划
   *
   * @param plans       计划列表
   * @param currentDate 当前日期
   * @return 之前的最后一个有效计划
   */
  private YaTeachingPlan findLastValidPlan(List<YaTeachingPlan> plans, String currentDate) {
    LocalDate current = LocalDate.parse(currentDate);

    // 按日期倒序查找
    for (int i = plans.size() - 1; i >= 0; i--) {
      YaTeachingPlan plan = plans.get(i);
      LocalDate planDate = LocalDate.parse(plan.getDate());

      // 找到当前日期之前的计划，且是有效教学日（有day字段）
      if (planDate.isBefore(current) && plan.getDay() != null) {
        return plan;
      }
    }
    return null;
  }

  /**
   * 更新后续所有计划的天数，确保连续性
   *
   * @param plans        所有计划
   * @param modifiedPlan 被修改的计划
   */
  private void updateSubsequentPlans(List<YaTeachingPlan> plans, YaTeachingPlan modifiedPlan) {
    LocalDate modifiedDate = LocalDate.parse(modifiedPlan.getDate());

    // 按日期排序所有计划
    plans.sort((p1, p2) -> LocalDate.parse(p1.getDate()).compareTo(LocalDate.parse(p2.getDate())));

    // 找到被修改计划在列表中的位置
    int modifiedIndex = -1;
    for (int i = 0; i < plans.size(); i++) {
      if (plans.get(i).getDate().equals(modifiedPlan.getDate())) {
        modifiedIndex = i;
        break;
      }
    }

    if (modifiedIndex != -1) {
      // 更新后续所有计划的天数
      for (int i = modifiedIndex + 1; i < plans.size(); i++) {
        YaTeachingPlan plan = plans.get(i);

        // 只更新那些已经有天数的计划（即原本就是教学日的计划）
        if (plan.getDay() != null) {
          plan.setDay(modifiedPlan.getDay() + (i - modifiedIndex));

          // 根据新的天数获取课程内容
          YaCourseDesign courseDesign = yaCourseDesignMapper.selectYaCourseDesignByDay(plan.getDay());
          if (courseDesign != null) {
            plan.setCourseContent(courseDesign.getCourseContent());
            plan.setCourseDesignId(courseDesign.getId());
          }

          // 更新数据库中的记录（如果已存在）
          if (plan.getId() != null) {
            yaTeachingPlanMapper.updateYaTeachingPlan(plan);
          }
        }
      }
    }
  }

  /**
   * 添加休息日
   *
   * @param yaTeachingPlan
   * @return
   */
  @Override
  public List<YaTeachingPlan> addHoliday(YaTeachingPlan yaTeachingPlan) {
    // 创建查询条件
    YaTeachingPlanDTO queryDTO = new YaTeachingPlanDTO();
    queryDTO.setClassName(yaTeachingPlan.getClassName());
    queryDTO.setStage(yaTeachingPlan.getStage());

    // 查询当前班级和阶段的所有计划
    List<YaTeachingPlan> list = yaTeachingPlanMapper.selectYaTeachingPlanListAll(queryDTO);

    // 查找要修改的计划项
    YaTeachingPlan targetPlan = null;
    for (YaTeachingPlan plan : list) {
      if (plan.getDate().equals(yaTeachingPlan.getDate())) {
        targetPlan = plan;
        break;
      }
    }

    // 如果找到了目标计划，且原本是工作日，则改为节假日
    if (targetPlan != null &&
      !"休息".equals(targetPlan.getCourseContent()) &&
      !"自习".equals(targetPlan.getCourseContent())) {

      // 设置为节假日类型（休息或自习）
      String holidayType = yaTeachingPlan.getType(); // 从前端传递的type字段获取
      if (holidayType == null || (!"休息".equals(holidayType) && !"自习".equals(holidayType))) {
        holidayType = "休息"; // 默认设置为休息
      }

      targetPlan.setCourseContent(holidayType);
      targetPlan.setDay(null); // 清空天数
      targetPlan.setCourseDesignId(null); // 清空课程设计ID
      targetPlan.setCourseDesignId(null);

      // 更新后续所有计划的天数，确保连续性
      updateSubsequentPlansForHoliday(list, targetPlan);

      // 更新数据库中的记录（如果已存在）
      if (targetPlan.getId() != null) {
        yaTeachingPlanMapper.updateYaTeachingHolidayPlan(targetPlan);
      }
    }

    return list;
  }

  /**
   * 更新后续所有计划的天数（当某天改为节假日时）
   *
   * @param plans        所有计划
   * @param modifiedPlan 被修改的计划
   */
  private void updateSubsequentPlansForHoliday(List<YaTeachingPlan> plans, YaTeachingPlan modifiedPlan) {
    // 按日期排序所有计划
    plans.sort((p1, p2) -> LocalDate.parse(p1.getDate()).compareTo(LocalDate.parse(p2.getDate())));

    // 找到被修改计划在列表中的位置
    int modifiedIndex = -1;
    for (int i = 0; i < plans.size(); i++) {
      if (plans.get(i).getDate().equals(modifiedPlan.getDate())) {
        modifiedIndex = i;
        break;
      }
    }

    if (modifiedIndex != -1) {
      // 更新后续所有计划的天数
      for (int i = modifiedIndex + 1; i < plans.size(); i++) {
        YaTeachingPlan plan = plans.get(i);

        // 只更新那些已经有天数的计划（即原本就是教学日的计划）
        if (plan.getDay() != null) {
          // 因为前一天改为节假日，所以后续所有教学日的天数都要减1
          plan.setDay(plan.getDay() - 1);

          // 根据新的天数获取课程内容
          YaCourseDesign courseDesign = yaCourseDesignMapper.selectYaCourseDesignByDay(plan.getDay());
          if (courseDesign != null) {
            plan.setCourseContent(courseDesign.getCourseContent());
            plan.setCourseDesignId(courseDesign.getId());
          }

          // 更新数据库中的记录（如果已存在）
          if (plan.getId() != null) {
            yaTeachingPlanMapper.updateYaTeachingPlan(plan);
          }
        }
      }
    }

  }
}


